<template>
	<view class="container">
		<u-search :showAction="true" actionText="搜索" :animation="true" :clearabled="true" placeholder="请输入姓名或学号"
			v-model="keyword" @custom="performSearch()" @clear="onClear()"></u-search>
		<view class="action-buttons">
			<u-button type="error" @click="deleteDialog=true">删除数据</u-button>
			<u-button type="primary" @click="importDialog=true">数据导入</u-button>
			<!-- 输入框，v-model 用于双向绑定，@blur 事件监听输入完成后执行搜索 -->
			<input v-model="moRenClass" @blur="search" :class="inputClass" placeholder="班级名" />
		</view>
		<!-- 弹出层 -->
		<u-popup :show="deleteDialog" mode="center" border-radius="10">
			<view style="padding: 20px; width: 80%; max-width: 400px; background-color: #fff;">
				<u--form labelPosition="left" ref="importForm">
					<u-form-item label="指定周数" borderBottom>
						<u--input v-model="deleteWeek" placeholder="请输入第几周(数字)"></u--input>
					</u-form-item>
				</u--form>
				<div style="display: flex; justify-content: space-between;">
					<u-button type="primary" text="确认" @click="showDeleteConfirm()"
						style="flex: 1; margin-right: 10px;"></u-button>
					<u-button color="#c8c9cc" text="取消" @click="deleteDialog=false" style="flex: 1;"></u-button>
				</div>
			</view>
		</u-popup>
		<!-- 弹出层 -->
		<u-popup :show="importDialog" mode="center" border-radius="10">
			<view style="padding: 20px; width: 80%; max-width: 400px; background-color: #fff;">
				<u--form labelPosition="left" :model="importLink" ref="importForm">
					<u-form-item label="数据链接" borderBottom>
						<u--input v-model="importLink.url" placeholder="请输入数据链接"></u--input>
					</u-form-item>
					<u-form-item label="周数" borderBottom>
						<u--input v-model="importLink.week" placeholder="请输入第几周(数字)"></u--input>
					</u-form-item>
				</u--form>
				<div style="display: flex; justify-content: space-between;">
					<u-button type="primary" text="确认" @click="confirmImport()"
						style="flex: 1; margin-right: 10px;"></u-button>
					<u-button color="#c8c9cc" text="取消" @click="importDialog=false" style="flex: 1;"></u-button>
				</div>
			</view>
		</u-popup>
		<div class="loader" v-if="loading"></div>
		<!-- 表格展示 -->
		<uni-table ref="table" border stripe emptyText="暂无更多数据">
			<!-- 表头 -->
			<uni-tr>
				<uni-th width="100" align="center" class="sticky-col">姓名</uni-th>
				<uni-th width="50" align="center">操作</uni-th>
				<uni-th width="50" align="center">学号</uni-th>
				<!-- 动态生成每周的表头 -->
				<uni-th v-for="week in weeks" :key="'header-' + week" :width="100" align="center">
					第{{ week }}周 成绩/排名
				</uni-th>
			</uni-tr>

			<!-- 数据行 -->
			<uni-tr v-for="(student, index) in students" :key="'row-' + student.student_id">
				<uni-td align="center" class="sticky-col" style="font-weight: bold;">{{ student.name }}</uni-td>
				<uni-td>
					<view class="uni-group">
						<button class="uni-button" size="mini" style="background-color: #CC99FF;"
							@click="goPerson(student)">Go</button>
					</view>
				</uni-td>
				<uni-td align="center">{{ student.student_id }}</uni-td>

				<!-- 对于每个学生，动态生成每周的成绩和排名 -->
				<uni-td v-for="week in weeks" :key="'cell-' + student.student_id + '-week-' + week" align="center">
					<view>成绩: {{ getScore(student.weeks, week) }}</view>
					<view>班排名: {{ getRanking(student.weeks, week) }}</view>
					<view>级排名: {{ getGradeRanking(student.weeks, week) }}</view>
				</uni-td>
			</uni-tr>
		</uni-table>
	</view>
</template>
<script>
	import * as XLSX from 'xlsx'; // 引入 xlsx 库
	export default {
		data() {
			return {
				keyword: '',
				moRenClass: uni.getStorageSync('默认班级') || '718', // 从缓存中读取默认班级
				students: [], // 学生列表
				weeks: [],
				deleteDialog: false, //删除框
				importDialog: false, //导入
				loading: false, // 控制加载图标的显示与隐藏
				deleteWeek: '',
				importLink: {
					url: '',
					week: ''
				},
				inputClass: 'default-input', // 默认样式类
				studenInfo: {
					name: '',
					student_id: '',
					week: '',
					score: ''
				},
			};
		},
		onLoad() {
			this.getData()
		},
		methods: {
			goPerson(student) {
				uni.setStorageSync(student.name + "年级版", student);
				uni.setStorageSync('周数年级版', this.weeks);
				uni.navigateTo({
					url: '/pages/index/gradePerson?name=' + student.name,
					animationType: 'fade-in',
					animationDuration: 200
				});
			},
			showDeleteConfirm(studentId) {
				uni.showModal({
					title: '提示',
					content: '确定要删除第' + this.deleteWeek + '周数据吗？',
					success: (res) => {
						if (res.confirm) {
							this.confirmDelete();
						} else if (res.cancel) {
							console.log('用户点击了取消');
						}
					}
				});
			},
			// 删除
			confirmDelete() {
				this.$dbUtils.delData('testDb', 'gradeScores', {
						week: this.deleteWeek
					})
					.then(response => {
						console.log("删除成功:", response);
						// 成功后可以刷新列表或做其他操作
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						// 
						let weekData = this.weeks.filter(week => week !== this.deleteWeek);
						uni.setStorageSync("龙湖四中周数", weekData);
						this.deleteDialog = false;
						// 假设你有一个方法来重新加载学生列表
						this.getData();
					})
					.catch(error => {
						console.error("删除失败:", error);
						uni.showToast({
							title: '删除失败，请稍后再试',
							icon: 'none'
						});
					});
			},
			// 搜索方法
			search() {
				console.log('搜索方法执行', this.moRenClass);
				uni.setStorageSync('默认班级', this.moRenClass); // 存储到本地缓存
				// 在这里可以执行你自己的搜索逻辑
				this.getData()
			},
			confirmImport() {
				console.log('正在访问:', this.importLink.url);
				// 访问链接获取数据的逻辑
				this.fetchAndParseExcel(this.importLink.url);
				this.importDialog = false
			},
			fetchAndParseExcel(url) {
				// 使用 uni.request 下载文件
				uni.request({
					url: url,
					method: 'GET',
					responseType: 'arraybuffer', // 确保以二进制格式接收文件
					success: (res) => {
						if (res.statusCode === 200) {
							// 下载成功，开始解析文件
							this.parseExcel(res.data);
						} else {
							console.error('文件下载失败:', res.statusCode);
						}
					},
					fail: (err) => {
						console.error('请求失败:', err);
					},
				});
			},

			// 解析 Excel 数据
			async parseExcel(data) {
				try {
					// 将二进制数据转换为工作簿对象
					const workbook = XLSX.read(data, {
						type: 'array'
					});

					// 选择要解析的工作表（假设是第一个工作表）
					const worksheet = workbook.Sheets[workbook.SheetNames[0]];

					// 将工作表转换为 JSON 格式（数组）
					const jsonData = XLSX.utils.sheet_to_json(worksheet, {
						header: 1
					}); // header: 1 表示使用第一行作为列标题
					// 将原始数据转换为目标格式
					let students = [];
					students = jsonData.slice(1).map(row => {
						return {
							student_class: row[0], // 班级
							name: row[1], // 姓名
							// score: row[4], // 成绩
							score: (row[4] !== undefined && row[4] !== null && !isNaN(row[4]) && !
									/[\u4e00-\u9fa5]/.test(row[4])) ?
								parseInt(row[4], 10) : 0,
							student_id: row[3], // 学号
							week: this.importLink.week, // 周数
						};
					});
					console.log('转换后的学生数据:', students);
					// 排序学生成绩，从高到低
					students.sort((a, b) => b.score - a.score);

					// 计算年级排名
					students.forEach((student, index) => {
						// 如果当前学生与前一个学生成绩相同，给当前学生相同的排名
						if (index > 0 && students[index].score === students[index - 1].score) {
							student.grade_rank = students[index - 1].grade_rank;
						} else {
							// 如果成绩不同，排名应该是当前索引加1
							student.grade_rank = index + 1;
						}
					});

					// 按班级分组
					const groupedByClass = students.reduce((acc, student) => {
						if (!acc[student.student_class]) {
							acc[student.student_class] = [];
						}
						acc[student.student_class].push(student);
						return acc;
					}, {});

					// 计算班级排名
					Object.keys(groupedByClass).forEach(className => {
						const classStudents = groupedByClass[className];

						// 按成绩从高到低排序
						classStudents.sort((a, b) => b.score - a.score);

						// 计算班级排名
						classStudents.forEach((student, index) => {
							// 处理成绩相同的学生，赋予相同排名
							if (index > 0 && classStudents[index].score === classStudents[index - 1]
								.score) {
								student.class_rank = classStudents[index - 1].class_rank;
							} else {
								student.class_rank = index + 1; // 排名从1开始
							}
						});
					});

					// 输出结果，检查是否正确
					console.log("==处理好的数组==:", students);
					this.loading = true;
					// 确保 both 为数字类型
					if (this.weeks.includes(Number(this.importLink.week))) {
						this.$dbUtils.delData('testDb', 'gradeScores', {
								week: Number(this.importLink.week)
							})
							.then(async (response) => {
								console.log("删除成功:", response);

								// 创建一个数组，存储所有 addTabItem 的 Promise
								const addPromises = students.map(item => this.$dbUtils.addTabItem('testDb',
									'gradeScores', item));

								// 使用 Promise.all 来并发执行所有的 addTabItem 操作
								await Promise.all(addPromises);

								console.log("更新成功");
							})
							.catch(error => {
								console.error("删除失败:", error);
								uni.showToast({
									title: '请先手动删除',
									icon: 'none'
								});
							});
					} else {
						// 插入数据到数据库
						for (const item of students) {
							await this.$dbUtils.addTabItem('testDb', 'gradeScores', item);
						}
						// uni.showToast({
						// 	title: '插入成功',
						// 	icon: 'success'
						// });
						// console.log("插入成功") 
					}
					// 插入完成后隐藏加载图标
					this.loading = false;
					this.getData();
				} catch (error) {
					console.error('Excel 解析失败:', error);
				}
			},
			// 清空时刷新
			onClear() {
				console.log('搜索框已清空');
				// 清空时执行查询的方法
				this.getData();
			},
			// 模拟搜索
			performSearch() {
				// 模拟搜索逻辑
				const value = this.keyword;
				if (value) {
					console.log(`正在搜索关键词: ${value}`);
					this.$dbUtils.selectXmXhDataLike('testDb', 'gradeScores', ['name', 'student_id'], value, {
							'student_class': this.moRenClass
						})
						.then(results => {
							console.log("模糊查询成功:", results);

							// Step 1: Group by student_id and name
							let groupedData = {};
							results.forEach(record => {
								if (!groupedData[record.student_id]) {
									groupedData[record.student_id] = {
										student_id: record.student_id,
										student_class: record.student_class,
										name: record.name,
										weeks: []
									};
								}
								groupedData[record.student_id].weeks.push({
									week: record.week,
									score: record.score,
									class_ranking: record.class_rank, // 直接使用数据库中的排名
									grade_ranking: record.grade_rank // 直接使用数据库中的排名						
								});
							});

							// Convert to array for easier manipulation
							let studentsArray = Object.values(groupedData);

							// Extract unique weeks from the results
							let weeks = Array.from(new Set(results.map(s => s.week))).sort((a, b) => a - b);

							// 更新组件状态
							this.students = studentsArray;
							this.weeks = weeks;
							console.log("查询学生:", this.students);
							console.log("查询周数:", this.weeks);
						})
						.catch(error => {
							console.error("模糊查询失败:", error);
						});
				} else {
					this.getData();
					console.warn('请输入搜索关键词');
				}
			},
			// 获取数据
			async getData() {
				try {
					const results = await this.$dbUtils.selectXmXhDataLike('testDb', 'gradeScores', ['name',
						'student_id'
					], this.keyword, {
						'student_class': this.moRenClass
					});
					console.log("查询成功:", results);

					// Step 1: Group by student_id and name
					let groupedData = {};
					results.forEach(record => {
						if (!groupedData[record.student_id]) {
							groupedData[record.student_id] = {
								student_id: record.student_id,
								student_class: record.student_class,
								name: record.name,
								weeks: []
							};
						}
						groupedData[record.student_id].weeks.push({
							week: record.week,
							score: record.score,
							class_ranking: record.class_rank, // 直接使用数据库中的排名
							grade_ranking: record.grade_rank // 直接使用数据库中的排名						
						});
					});

					// Convert to array for easier manipulation
					let studentsArray = Object.values(groupedData);

					// Extract unique weeks from the results
					let weeks = Array.from(new Set(results.map(s => s.week))).sort((a, b) => a - b);

					// 更新组件状态
					this.students = studentsArray;
					this.weeks = weeks;
					console.log("查询学生:", this.students);
					console.log("查询周数:", this.weeks);
					uni.showToast({
						title: '查询成功',
						icon: 'success'
					});

				} catch (error) {
					console.error("查询失败:", error);
				}
			},
			getScore(weeks, week) {
				const weekData = weeks.find(w => w.week === week);
				return weekData ? weekData.score : '-';
			},
			getRanking(weeks, week) {
				const weekData = weeks.find(w => w.week === week);
				return weekData ? weekData.class_ranking : '-';
			},
			getGradeRanking(weeks, week) {
				const weekData = weeks.find(w => w.week === week);
				return weekData ? weekData.grade_ranking : '-';
			},
		}
	};
</script>
<style scoped>
	.sticky-col {
		position: sticky;
		left: 0;
		/* background-color: #fafafa; */
		background-color: #fafafa;
		/* 可以设置背景色，避免背景与滚动内容重叠 */
		z-index: 1;
		color: black;
		/* 确保固定列在前 */
	}

	th.sticky-col {
		z-index: 2;
		/* 确保表头固定 */
	}

	.loader {
		position: fixed;
		/* 固定定位 */
		top: 50%;
		/* 垂直居中 */
		left: 50%;
		/* 水平居中 */
		transform: translate(-50%, -50%);
		/* 通过偏移使其真正居中 */
		width: 50px;
		aspect-ratio: 1;
		display: grid;
		z-index: 999;
	}

	.loader::before,
	.loader::after {
		content: "";
		grid-area: 1/1;
		--c: no-repeat radial-gradient(farthest-side, #25b09b 92%, #0000);
		background:
			var(--c) 50% 0,
			var(--c) 50% 100%,
			var(--c) 100% 50%,
			var(--c) 0 50%;
		background-size: 12px 12px;
		animation: l12 1s infinite;
	}

	.loader::before {
		margin: 4px;
		filter: hue-rotate(45deg);
		background-size: 8px 8px;
		animation-timing-function: linear;
	}

	@keyframes l12 {
		100% {
			transform: rotate(.5turn);
		}
	}


	/* 默认输入框样式 */
	.default-input {
		padding: 10px;
		border: 1px solid #ccc;
		border-radius: 4px;
		width: 100%;
		font-size: 14px;
	}

	/* 聚焦时的输入框样式 */
	.default-input:focus {
		border-color: #66afe9;
		outline: none;
		box-shadow: 0 0 8px rgba(102, 175, 233, 0.6);
	}

	/* 鼠标悬停时输入框样式 */
	.default-input:hover {
		border-color: #888;
	}

	.container {
		padding: 20rpx;
	}

	.action-buttons {
		margin-top: 20rpx;
		margin-bottom: 20rpx;
		display: flex;
		flex-direction: row;
		/* 默认是row，可省略 */
		justify-content: space-between;
		/* 根据需要调整对齐方式 */
		gap: 10px;
		/* 按钮之间的间距 */
	}

	.student-table {
		margin-top: 20rpx;
	}

	.form-content {
		padding: 20rpx;
	}

	.delete-content {
		text-align: center;
		padding: 20rpx;
	}

	.uni-group {
		display: flex;
		align-items: center;
	}

	.u-page {
		padding: 0;
	}

	.u-cell-icon {
		width: 36rpx;
		height: 36rpx;
		margin-right: 8rpx;
	}

	.u-cell-group__title__text {
		font-weight: bold;
	}
</style>